<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Includes the Nested_Set_Model class as well as the required sub-classes
 * @package codeigniter.application.models
 */

/**
 * User_Nested_Set_Model extends codeigniters base CI_Model to inherit all codeigniter magic!
 * @author Com-RT
 * @package codeigniter.application.models
 */
class Comment_Model extends CI_Model {
    /*
     * A private variable to represent each column in the database-table
     */

    private $tablename = 'comment';

    function __construct() {
        parent::__construct();
    }

    function getItem($id) {
        $item = $this->db->get_where($this->tablename, array('id' => $id));
        return $item->row(); //gibt eine row als Objekt zurück
    }

    function getItems() {
        
//        $items = $this->db->get($this->tablename);
        $items = $this->db->query('SELECT n.id, n.text, n.title, n.lft, n.rgt, COUNT(*)-1 AS level FROM comment AS n, comment AS p WHERE n.lft BETWEEN p.lft AND p.rgt GROUP BY n.lft ORDER BY n.lft;');
        return $items->result(); //gibt die ergebnisse als array von Objekten zurück
    }

    //object reinreichen, id des Objekts zurückbekommen
    function update($item) {
        $this->db->where('id', $item->id);
        $this->db->update($this->tablename, $item);
    }

    //mit insert-id rückgabe
    function insert($item) {
        $this->db->query('UPDATE comment SET rgt=rgt+2 WHERE rgt >= '.$item->rgt);
        $this->db->query('UPDATE comment SET lft=lft+2 WHERE lft > '.$item->rgt);
        $this->db->query('INSERT INTO comment (title, text, lft, rgt) VALUES (\''.$item->title.'\', \''.$item->text.'\', '.$item->rgt.', '.(int)$item->rgt.' + 1)');
        
//        $this->db->insert($this->tablename, $item);

        $insert_id = $this->db->insert_id();
        $this->db->trans_complete();
        return $insert_id;
    }

    function delete($item) {
        $this->db->delete($this->tablename, array('id' => $item->id));
    }

    
}
